package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl  implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHQRE = "seckill:stock:";

    @Override
    public void uploadSeckillSkuLates30Days() {
        //最近三天需要参与秒杀的活动
        R session = couponFeignService.getLates30DaySession();
        if (session.getCode() == 0){
            List<SeckillSessionWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSessionWithSkus>>(){});

            //缓存到redis
            //1.缓存活动信息
            saveSessionInfos(sessionData);

            //2、缓存活动的关联商品信息
            saveSessionSkuInfos(sessionData);

        }
    }

    public List<SeckillSkuRedisTo> blockHandler() {
        System.out.println("被限流了。。。");
        return null;
    }
    //   * 获取当前时间可以参与秒杀的商品信息
    @Override
    @SentinelResource(value="getCurrentSeckillSkus",blockHandler="blockHandler")
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        long time = System.currentTimeMillis();
        //1、确定当前时间属于哪个秒杀场次
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys){
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");

            String[] s = replace.split("_");
            Long start = Long.parseLong(s[0]);
            Long end = Long.parseLong(s[1]);
            if (time >= start && time <= end) {
                //2、获取这个秒杀场次需要的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                if(list!=null && list.size()>0){
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                        return seckillSkuRedisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }

        return null;
    }

    /**
     * 获取当前商品的秒杀信息
     *
     * @param skuId
     * @return
     */
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //1、找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if(keys!=null && keys.size()>0){
            for (String key : keys){
                String regx = "\\d_" + skuId;
                if (Pattern.matches(regx,key)){
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);

                    long time = System.currentTimeMillis();
                    // 时间没到秒杀时间，则随机码是null
                    if (time >= seckillSkuRedisTo.getStartTime() && time <= seckillSkuRedisTo.getEndTime()){
                    }else {
                        seckillSkuRedisTo.setRandomCode(null);
                    }
                    return seckillSkuRedisTo;
                }
            }
        }

        return null;
    }

    /**
     * 秒杀商品
     * 后续 上架秒杀商品时候，每一个数据都有过期时间
     * 秒杀后续的流程，简化收获地址等信息
     * 秒杀开始锁定库存，最后看信号量来释放库存
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo loginUser = LoginUserInterceptor.threadLocal.get();

        // 获取秒杀产品相应信息
        BoundHashOperations<String, String, String> hashOps =
                redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        String json = hashOps.get(killId);
        if (StringUtils.isNotEmpty(json)){
            SeckillSkuRedisTo redis = JSON.parseObject(json, SeckillSkuRedisTo.class);
            // 1 判断时间
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long currentTime = System.currentTimeMillis();
            long ttl = endTime - currentTime;

            if (currentTime >= startTime && currentTime <= endTime) {
                // 2 随机码
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && skuId.equals(killId)){
                    // 3 检验数量
                    if (num <= redis.getSeckillLimit()){
                        //4 验证这个用户是否已经参与过秒杀、未参与就占位
                        String redisKey = loginUser.getId() + "_" + skuId;
                        Boolean isBuy = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (isBuy){
                            // 说明从未买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHQRE + randomCode);


                                boolean b = semaphore.tryAcquire(num);
                                if (b){
                                    System.out.println("秒杀成功，发送mq消息");
                                    //秒杀成功
                                    //快速下单、发送MQ消息
                                    String order_sn = IdWorker.getTimeId();
                                    SeckillOrderTo seckillOrderTo = new SeckillOrderTo() ;
                                    seckillOrderTo.setOrderSn(order_sn);
                                    seckillOrderTo.setMemberId(loginUser.getId());
                                    seckillOrderTo.setNum(num);
                                    seckillOrderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                    seckillOrderTo.setSeckillPrice(redis.getSeckillPrice());
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrderTo);
                                    return order_sn;

                                }


                        }

                    }else {
                        return null;
                    }


                }else {
                    return null;
                }

            }else {
                return  null;
            }



        }
        return null;
    }

    /**
     * 缓存活动的关联商品信息
     * @param sessionData
     */
    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> sessionData) {

        sessionData.stream().forEach(session->{
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            String token = UUID.randomUUID().toString().replace("-", "");
            session.getRelationSkus().stream().forEach(seckillSkuVo->{
                if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString())){
                    // 缓存商品
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    // 1、skuinfo
                    R r = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (r.getCode()==0){
                        SkuInfoVo skuInfo = r.getData(new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(skuInfo);
                    }

                    // 2、 sku 秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,redisTo);

                    // 3、 设置当前商品的秒杀时间
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    // 4、 随机码、
                    redisTo.setRandomCode(token);

                    // 5、 库存作为redis 信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHQRE + token);
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());

                    String values = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(),values);


                }
            });
        });
    }

    /**
     *  缓存活动信息
     * @param sessionData
     */
    private void saveSessionInfos(List<SeckillSessionWithSkus> sessionData) {
        sessionData.stream().forEach(session->{
            long start = session.getCreateTime().getTime();
            long end = session.getEndTime().getTime();

            String key = SESSIONS_CACHE_PREFIX + start + "_" + end;
            // 检查是否缓存过
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey){
                List<String> values = session.getRelationSkus().stream().map(item ->
                        item.getPromotionSessionId() + "_" + item.getSkuId().toString()
                ).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,values);
            }
            
        });
    }
}
